package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String path; 
    
    /**
     * 文件上传
     * @param file
     * MultipartFile: 文件上传项,此对象中包含了上传的文件的所有信息
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        log.info("上传的文件: "+file);
        // 获取文件的名称
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        // 截取上传的文件的扩展名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成一个唯一的文件名称
        String filename = UUID.randomUUID().toString() + suffix;
        // 判断保存图片的目录是否存在
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        // 保存上传的文件
        file.transferTo(new File(path+filename));
        return R.success(filename);
    }

    /**
     * 文件下载
     * @param name
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response,HttpServletRequest request) {
        try {
            log.info("要下载的文件名: "+name);
            //1.读取服务器上要被下载的文件
            FileInputStream is = new FileInputStream(new File(path + name));
            //2.获取响应输出流
            ServletOutputStream os = response.getOutputStream();
            ServletContext servletContext = request.getServletContext();
            String mimeType = servletContext.getMimeType(name);
            System.out.println("文件的类型: "+mimeType);
            // 设置响应文件的mime类型
            response.setContentType(mimeType);
            // 设置文件下载专用头
            response.setHeader("content-disposition","attachment;filename="+name);
            //3.文件拷贝
            int len = 0;
            byte []buffer = new byte[1024];
            while ((len=is.read(buffer))!=-1){
                os.write(buffer,0,len);
                os.flush();
            }
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}    